using Universal.Application.Contracts.Storage;

namespace Universal.Infrastructure.Storage;

/// <summary>
/// 本地文件存储实现类
/// </summary>
public class LocalFileStorage : IFileStorage
{

    private readonly string _baseDir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads");

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    public Task DeleteFileAsync(string filePath)
    {
        var fullPath = Path.Combine(_baseDir, filePath.TrimStart('/'));
        if (File.Exists(fullPath))
            File.Delete(fullPath);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 获取文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    public Task<Stream> GetFileAsync(string filePath)
    {
        var fullPath = Path.Combine(_baseDir, filePath.TrimStart('/'));
        if (!File.Exists(fullPath))
            throw new FileNotFoundException("文件不存在", fullPath);

        Stream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
        return Task.FromResult(stream);
    }

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="fileStream">文件流</param>
    /// <param name="fileName">文件名</param>
    public async Task<string> SaveFileAsync(Stream fileStream, string fileName)
    {
        Directory.CreateDirectory(_baseDir);
        var savePath = Path.Combine(_baseDir, fileName);

        using (var stream = new FileStream(savePath, FileMode.Create))
        {
            await fileStream.CopyToAsync(stream);
        }

        // 返回前端可直接访问的相对路径
        return $"/uploads/{fileName}";
    }
}